package com.longge.wechat.thread;

public class ProducerConsumer {
	public static void main(String[] args) {
		Basket basket = new Basket();
		Producer p = new Producer(basket);
		Consumer c = new Consumer(basket);
		new Thread(p).start();
		new Thread(p).start();
		new Thread(p).start();
		new Thread(c).start();
		new Thread(c).start();
		new Thread(c).start();
	}
}

class ManTou {
	int id;

	public ManTou(int id) {
		super();
		this.id = id;
	}
	
	public String toString() {
		return "馒头id值:"+id;
	}
}

class Basket {
	int index = 0;
	ManTou[] mt = new ManTou[6];
	
	public synchronized void push(ManTou mTou) {
		while (index == mt.length) {
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		this.notifyAll();
		mt[index] = mTou;
		index ++;
	}
	
	public synchronized ManTou pop() {
		while (index == 0) {
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		this.notifyAll();
		index --;
		return mt[index];
	}
}


class Producer implements Runnable{
	Basket basket = null;
	
	public Producer(Basket basket) {
		super();
		this.basket = basket;
	}

	@Override
	public void run() {
		for (int i = 0; i < 10; i++) {
			ManTou manTou = new ManTou(i);
			basket.push(manTou);
			System.out.println("生产者生产了"+manTou);
			try {
				Thread.sleep((int)(Math.random()*100));
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

class Consumer implements Runnable{
	Basket basket = null;

	public Consumer(Basket basket) {
		super();
		this.basket = basket;
	}

	@Override
	public void run() {
		for (int i = 0; i < 10; i++) {
			ManTou mat = basket.pop();
			System.out.println("消费者消费了"+mat);
			try {
				Thread.sleep((int)(Math.random()*100));
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}